/**
 * JDBM LICENSE v1.00
 *
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. The name "JDBM" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of Cees de Groot.  For written permission,
 *    please contact cg@cdegroot.com.
 *
 * 4. Products derived from this Software may not be called "JDBM"
 *    nor may "JDBM" appear in their names without prior written
 *    permission of Cees de Groot.
 *
 * 5. Due credit should be given to the JDBM Project
 *    (http://jdbm.sourceforge.net/).
 *
 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
 * Contributions are Copyright (C) 2000 by their associated contributors.
 *
 * $Id: BlockIo.java,v 1.2 2002/08/06 05:18:36 boisvert Exp $
 */

package com.sunchangming.stmdb.recman;

import java.io.IOException;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;

/**
 * 以page size为单位的block
 * 
 * @see java.io.DataInput
 * @see java.io.DataOutput
 */
public final class BlockIo {
	private final static Logger logger = LoggerFactory.getLogger(BlockIo.class);

	public boolean isSameData(BlockIo o) {
		return this.blockId == o.blockId && Arrays.equals(this.data, o.data);
	}

	private long blockId;

	private transient byte[] data; // work area
	private transient BlockView view = null;
	private transient boolean dirty = false;
	private transient int transactionCount = 0;

	/**
	 * Default constructor for serialization
	 */
	private BlockIo() {
		// empty
	}

	/**
	 * Constructs a new BlockIo instance working on the indicated buffer.
	 */
	BlockIo(long blockId, byte[] data) {
		this.blockId = blockId;
		this.data = data;
	}

	/**
	 * Returns the underlying array
	 */
	byte[] getData() {
		return data;
	}

	/**
	 * Sets the block number. Should only be called by RecordFile.
	 */
	void setBlockId(long id) {
		if (isInTransaction())
			throw new Error("BlockId assigned for transaction block");
		blockId = id;
	}

	/**
	 * Returns the block number.
	 */
	long getBlockId() {
		return blockId;
	}

	/**
	 * Returns the current view of the block.
	 */
	public BlockView getView() {
		return view;
	}

	/**
	 * Sets the current view of the block.
	 */
	public void setView(BlockView view) {
		this.view = view;
	}

	/**
	 * Sets the dirty flag
	 */
	void setDirty() {
		dirty = true;
	}

	/**
	 * Clears the dirty flag
	 */
	void setClean() {
		dirty = false;
	}

	/**
	 * Returns true if the dirty flag is set.
	 */
	boolean isDirty() {
		return dirty;
	}

	/**
	 * Returns true if the block is still dirty with respect to the transaction
	 * log.
	 */
	boolean isInTransaction() {
		return transactionCount != 0;
	}

	/**
	 * Increments transaction count for this block, to signal that this block is
	 * in the log but not yet in the data file. The method also takes a snapshot
	 * so that the data may be modified in new transactions.
	 */
	synchronized void incrementTransactionCount() {
		transactionCount++;
		// @fixme(alex)
		setClean();
	}

	/**
	 * Decrements transaction count for this block, to signal that this block
	 * has been written from the log to the data file.
	 */
	synchronized void decrementTransactionCount() {
		transactionCount--;
		if (transactionCount < 0)
			throw new Error("transaction count on block " + getBlockId() + " below zero!");

	}


	/**
	 * Reads an int from the indicated position
	 */
	public int readInt(int pos) {
		try {
			return CodedInputStream.newInstance(data, pos, data.length - pos).readInt32();
		} catch (final java.io.IOException ex) {
			logger.error("err", ex);
			throw new RuntimeException(ex);
		}
	}

	/**
	 * Writes an int to the indicated position
	 */
	public void writeInt(int pos, int value) {
		try {
			CodedOutputStream.newInstance(data, pos, data.length - pos).writeInt32NoTag(value);
		} catch (final java.io.IOException ex) {
			logger.error("err", ex);
		}
		setDirty();
	}

	/**
	 * Reads a long from the indicated position
	 */
	public long readLong(int pos) {
		try {
			return CodedInputStream.newInstance(data, pos, data.length - pos).readInt64();
		} catch (final java.io.IOException ex) {
			logger.error("err", ex);
			throw new RuntimeException(ex);
		}
	}

	/**
	 * Writes a long to the indicated position
	 */
	public void writeLong(int pos, long value) {
		try {
			CodedOutputStream.newInstance(data, pos, data.length - pos).writeInt64NoTag(value);
		} catch (final java.io.IOException ex) {
			logger.error("err", ex);
		}
		setDirty();
	}

	@Override
	public String toString() {
		return "BlockIo [blockId=" + blockId + ", view=" + view + ", dirty=" + dirty + "]";
	}

	public static BlockIo read(CodedInputStream in) throws IOException {
		final BlockIo ret = new BlockIo();
		ret.blockId = in.readInt64();
		final int length = in.readInt32();
		ret.data = in.readRawBytes(length);
		return ret;
	}

	public void write(CodedOutputStream out) throws IOException {
		out.writeInt64NoTag(blockId);
		out.writeInt32NoTag(data.length);
		out.writeRawBytes(data);
	}

}
